#include "transcoder_core.h"
char *SRC_FILENAME;
sem_t ALIVED_DEC_THREAD_CNT;
int REFCOUNT = 0;

int open_codec_context(int *stream_idx,
		AVFormatContext *fmt_ctx, enum AVMediaType type)
{
	int ret, stream_index;
	AVStream *st;
	AVCodecContext *dec_ctx = NULL;
	AVCodec *dec = NULL;
	AVDictionary *opts = NULL;

	ret = av_find_best_stream(fmt_ctx, type, -1, -1, NULL, 0);
	if (ret < 0) {
		fprintf(stdout, "Error 24: Could not find %s stream in input file '%s'\n",
				av_get_media_type_string(type), SRC_FILENAME);
		return ret;
	} else {
		stream_index = ret;
		st = fmt_ctx->streams[stream_index];

		/* find decoder for the stream */
		dec_ctx = st->codec;
		dec = avcodec_find_decoder(dec_ctx->codec_id);
		if (!dec) {
			fprintf(stdout, "Error 25: Failed to find %s codec\n",
					av_get_media_type_string(type));
			return AVERROR(EINVAL);
		}

		dec_ctx->thread_count = 1;

		/* Init the decoders, with or without reference counting */
		av_dict_set(&opts, "refcounted_frames", REFCOUNT ? "1" : "0", 0);
		if ((ret = avcodec_open2(dec_ctx, dec, &opts)) < 0) {
			fprintf(stdout, "Error 26: Failed to open %s codec\n",
					av_get_media_type_string(type));
			return ret;
		}
		*stream_idx = stream_index;
	}
	return 0;
}



bool is_i_frame(AVFrame *frame) {
	return frame->pict_type == AV_PICTURE_TYPE_I;
}

bool is_key_frame(AVFrame *frame) {
	return frame->key_frame == 1;
}

// RETURNS: the string representation of the frame;
char* get_frame_type(AVFrame *frame) {
	switch (frame->pict_type) {
		case AV_PICTURE_TYPE_I:
			return "I";
		case AV_PICTURE_TYPE_P:
			return "P";
		case AV_PICTURE_TYPE_B:
			return "B";
		default:
			return "Not I/P/B";
	}
}

void initialize(){
	av_register_all();
	sem_init(&ALIVED_DEC_THREAD_CNT, 0, 0);
	initialize_decode_data(); 
	initialize_encode_data(); 
	core_binding_initialize();
}


